<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后端连接测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            border-bottom: 2px solid #1890ff;
            padding-bottom: 10px;
        }
        .test-item {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .test-item h3 {
            margin-top: 0;
            color: #1890ff;
        }
        button {
            background-color: #1890ff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin-right: 10px;
        }
        button:hover {
            background-color: #40a9ff;
        }
        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .result {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
            font-family: monospace;
            white-space: pre-wrap;
            word-break: break-all;
        }
        .success {
            background-color: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #52c41a;
        }
        .error {
            background-color: #fff2f0;
            border: 1px solid #ffccc7;
            color: #ff4d4f;
        }
        .info {
            background-color: #e6f7ff;
            border: 1px solid #91d5ff;
            color: #1890ff;
        }
        .config {
            background-color: #fffbe6;
            border: 1px solid #ffe58f;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        .config h3 {
            margin-top: 0;
            color: #faad14;
        }
        input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 后端连接测试工具</h1>
        
        <div class="config">
            <h3>⚙️ 配置</h3>
            <label>后端地址:</label>
            <input type="text" id="backendUrl" value="http://192.168.1.22:11500" placeholder="http://192.168.1.22:11500">
            <label>用户名:</label>
            <input type="text" id="username" value="admin" placeholder="admin">
            <label>密码:</label>
            <input type="password" id="password" value="123456" placeholder="123456">
        </div>

        <div class="test-item">
            <h3>测试 1: 检查后端服务是否可访问</h3>
            <p>尝试访问后端根路径，检查服务是否在线</p>
            <button onclick="testBackendRoot()">开始测试</button>
            <div id="result1" class="result" style="display:none;"></div>
        </div>

        <div class="test-item">
            <h3>测试 2: 测试登录接口</h3>
            <p>尝试调用登录接口: POST /auth/api/login</p>
            <button onclick="testLogin()">开始测试</button>
            <div id="result2" class="result" style="display:none;"></div>
        </div>

        <div class="test-item">
            <h3>测试 3: 测试部门树接口</h3>
            <p>尝试调用部门树接口: POST /api/dept/tree (需要先登录)</p>
            <button onclick="testDeptTree()" id="deptTreeBtn" disabled>开始测试</button>
            <div id="result3" class="result" style="display:none;"></div>
        </div>

        <div class="test-item">
            <h3>测试 4: CORS 跨域检查</h3>
            <p>检查后端是否配置了正确的 CORS 策略</p>
            <button onclick="testCORS()">开始测试</button>
            <div id="result4" class="result" style="display:none;"></div>
        </div>
    </div>

    <script>
        let accessToken = null;

        function showResult(elementId, message, type) {
            const element = document.getElementById(elementId);
            element.style.display = 'block';
            element.className = `result ${type}`;
            element.textContent = message;
        }

        async function testBackendRoot() {
            const backendUrl = document.getElementById('backendUrl').value;
            showResult('result1', '正在测试...', 'info');
            
            try {
                const response = await fetch(backendUrl, {
                    method: 'GET',
                    mode: 'cors',
                });
                
                const text = await response.text();
                showResult('result1', 
                    `✅ 成功连接到后端服务！\n` +
                    `状态码: ${response.status}\n` +
                    `响应内容: ${text.substring(0, 200)}${text.length > 200 ? '...' : ''}`,
                    'success'
                );
            } catch (error) {
                showResult('result1', 
                    `❌ 连接失败！\n` +
                    `错误信息: ${error.message}\n\n` +
                    `可能的原因:\n` +
                    `1. 后端服务未启动\n` +
                    `2. IP地址或端口错误\n` +
                    `3. 网络连接问题\n` +
                    `4. 防火墙阻止了连接`,
                    'error'
                );
            }
        }

        async function testLogin() {
            const backendUrl = document.getElementById('backendUrl').value;
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            showResult('result2', '正在测试登录...', 'info');
            
            try {
                const response = await fetch(`${backendUrl}/auth/api/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ username, password }),
                });
                
                const data = await response.json();
                
                if (response.ok || data.respCode === 0) {
                    // 保存 token
                    if (data.datas && data.datas.accessToken) {
                        accessToken = data.datas.accessToken;
                        document.getElementById('deptTreeBtn').disabled = false;
                    }
                    
                    showResult('result2', 
                        `✅ 登录成功！\n` +
                        `状态码: ${response.status}\n` +
                        `响应数据: ${JSON.stringify(data, null, 2)}`,
                        'success'
                    );
                } else {
                    showResult('result2', 
                        `❌ 登录失败！\n` +
                        `状态码: ${response.status}\n` +
                        `错误信息: ${data.respMsg || data.message || '未知错误'}\n` +
                        `响应数据: ${JSON.stringify(data, null, 2)}`,
                        'error'
                    );
                }
            } catch (error) {
                showResult('result2', 
                    `❌ 请求失败！\n` +
                    `错误信息: ${error.message}\n\n` +
                    `可能的原因:\n` +
                    `1. 后端登录接口路径错误\n` +
                    `2. 请求格式不正确\n` +
                    `3. CORS 跨域问题\n` +
                    `4. 网络连接中断`,
                    'error'
                );
            }
        }

        async function testDeptTree() {
            const backendUrl = document.getElementById('backendUrl').value;
            
            if (!accessToken) {
                showResult('result3', '❌ 请先登录获取 token！', 'error');
                return;
            }
            
            showResult('result3', '正在测试部门树接口...', 'info');
            
            try {
                const response = await fetch(`${backendUrl}/api/dept/tree`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${accessToken}`,
                    },
                    body: JSON.stringify({}),
                });
                
                const data = await response.json();
                
                if (response.ok || data.respCode === 0) {
                    showResult('result3', 
                        `✅ 部门树接口调用成功！\n` +
                        `状态码: ${response.status}\n` +
                        `响应数据: ${JSON.stringify(data, null, 2).substring(0, 500)}...`,
                        'success'
                    );
                } else {
                    showResult('result3', 
                        `❌ 接口调用失败！\n` +
                        `状态码: ${response.status}\n` +
                        `错误信息: ${data.respMsg || data.message || '未知错误'}\n` +
                        `响应数据: ${JSON.stringify(data, null, 2)}`,
                        'error'
                    );
                }
            } catch (error) {
                showResult('result3', 
                    `❌ 请求失败！\n` +
                    `错误信息: ${error.message}`,
                    'error'
                );
            }
        }

        async function testCORS() {
            const backendUrl = document.getElementById('backendUrl').value;
            showResult('result4', '正在检查 CORS 配置...', 'info');
            
            try {
                const response = await fetch(`${backendUrl}/auth/api/login`, {
                    method: 'OPTIONS',
                    headers: {
                        'Origin': window.location.origin,
                        'Access-Control-Request-Method': 'POST',
                        'Access-Control-Request-Headers': 'Content-Type',
                    },
                });
                
                const corsHeaders = {
                    'Access-Control-Allow-Origin': response.headers.get('Access-Control-Allow-Origin'),
                    'Access-Control-Allow-Methods': response.headers.get('Access-Control-Allow-Methods'),
                    'Access-Control-Allow-Headers': response.headers.get('Access-Control-Allow-Headers'),
                    'Access-Control-Allow-Credentials': response.headers.get('Access-Control-Allow-Credentials'),
                };
                
                showResult('result4', 
                    `✅ CORS 预检请求成功！\n` +
                    `状态码: ${response.status}\n` +
                    `CORS 响应头:\n${JSON.stringify(corsHeaders, null, 2)}\n\n` +
                    `${corsHeaders['Access-Control-Allow-Origin'] ? '✅ 允许跨域访问' : '❌ 未配置跨域'}`,
                    corsHeaders['Access-Control-Allow-Origin'] ? 'success' : 'error'
                );
            } catch (error) {
                showResult('result4', 
                    `❌ CORS 检查失败！\n` +
                    `错误信息: ${error.message}\n\n` +
                    `这通常意味着后端未配置 CORS 策略，需要在后端添加:\n` +
                    `@CrossOrigin 注解或全局 CORS 配置`,
                    'error'
                );
            }
        }
    </script>
</body>
</html>

